﻿using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace IoTSignalR
{
    public class AnonymousPipeProtocol:IGeneralPipeProtocol
    {
        private readonly AnonymousPipeServer _anonymousPipeServer;
        //为了在中介者中选择协议去发送数据
        public event EventHandler<ProtocolNotifyEventArg> ReceiveMessagesAfter;
        public event EventHandler<ProtocolNotifyEventArg> SendMessagesAfter;
        public event EventHandler<ProtocolNotifyEventArg> OnConnectedAfter;
        public event EventHandler<ProtocolNotifyEventArg> OnDisconnectedAfter;    
        public AnonymousPipeProtocol(string childProcessPath, int maxConnectionCount)
        {
            _anonymousPipeServer = new AnonymousPipeServer(childProcessPath, maxConnectionCount);
            _anonymousPipeServer.OnConnected += (sender, args) =>
            {
                OnConnectedAfter.Invoke(this, new ProtocolNotifyEventArg(args,ProtocolEnum.AnonymousPipe));
            };
            _anonymousPipeServer.OnDisconnected += (sender, args) =>
            {
                OnDisconnectedAfter.Invoke(this, new ProtocolNotifyEventArg(args, ProtocolEnum.AnonymousPipe));
            };
            _anonymousPipeServer.OnReceiveErro += (sender, args) =>
            {
                Console.WriteLine($"接收异常:{args.ClientId + " | " + args.Message}");
            };
            _anonymousPipeServer.OnSendErro += (sender, args) =>
            {
                Console.WriteLine($"发送异常:{args.ClientId + " | " + args.Message}");
            };
            _anonymousPipeServer.OnBusError += (sender, args) =>
            {
                Console.WriteLine($"总线错误:{args}");
            };
            _anonymousPipeServer.ReceiveMessagesAfter += (sender, args) =>
            {
                ReceiveMessagesAfter.Invoke(this, new ProtocolNotifyEventArg(args, ProtocolEnum.AnonymousPipe));
            };
            _anonymousPipeServer.SendMessageAfter += (sender, args) =>
            {
                SendMessagesAfter.Invoke(this, new ProtocolNotifyEventArg(args, ProtocolEnum.AnonymousPipe));
            };
            _anonymousPipeServer.Start();
            Console.WriteLine($"匿名管道协议已启动");
        }
        public async Task SendMsg(string clientId, string msg)
        {
            await _anonymousPipeServer.SendMessage(clientId, msg);
        }
        public async Task SendGroupMsg(string clientId, string msg)
        {
            await _anonymousPipeServer.SendGroupMessage(clientId, msg);
        }
    }
}
